#!/bin/bash

#functions
startLogin() {
	if [ -z $CENTERPID ]; then
		./corecenter corecenter.xml &
		echo "corecenter starting..."
		sleep 2
	else
		echo "corecenter is running, skip..."
	fi

	if [ -z $LOGINPID ]; then
		./loginmgr loginmgr.xml &
		echo "loginmgr starting..."
	else
		echo "loginmgr is running, skip..."
	fi
}

stopLogin() {
	if [ -z $LOGINPID ]; then
		echo "no loginmgr is running, skip..."
	else
		while [ -n `pgrep loginmgr` ]; do 
			kill $LOGINPID
			echo "kill loginmgr($LOGINPID), wait..."
			sleep 2;
		done
		echo "loginmgr is dead"
	fi

	sleep 1;

	if [ -z $CENTERPID ]; then
		echo "no corecenter is running, skip..."
	else
		while [ -n `pgrep corecenter` ]; do 
			kill $CENTERPID
			echo "kill corecenter($CENTERPID), wait..."
			sleep 2
		done
		echo "corecenter is dead"
	fi
}

startIM() {
	if [ -z $IMCENTERPID ]; then
		./imcenter imcenter.xml &
		echo "imcenter starting..."
		sleep 2
	else
		echo "imcenter is running, skip..."
	fi

	if [ -z $SMPID ]; then
		./session sm.xml &
		echo "session1 starting..."
		sleep 1
		./session sm.xml &
		echo "session2 starting..."
		sleep 2
	else
		echo "session is running, skip..."
	fi

	if [ -z $FRONTPID ]; then
		./front front.xml &
		echo "front starting..."
		sleep 2
	else
		echo "front is running, skip..."
	fi
}
stopIM() {
	if [ -z $FRONTPID ]; then
		echo "no front is running, skip..."
	else
		while [ -n `pgrep front` ]; do 
			kill $FRONTPID
			echo "kill front($FRONTPID), wait..."
			sleep 2
		done
		echo "front is dead"
	fi

	sleep 1;

	if [ -z $SMPID ]; then
		echo "no session is running, skip..."
	else
		while [ -n `pgrep session` ]; do 
			$SMPID=`pgrep session | sed -n '1p'`
			kill $SMPID
			echo "kill session($SMPID), wait..."
			sleep 2
		done
		echo "all session is dead"
	fi

	sleep 1;

	if [ -z $IMCENTERPID ]; then
		echo "no imcenter is running, skip..."
	else
		while [ -n `pgrep imcenter` ]; do 
			kill $IMCENTERPID
			echo "kill imcenter($IMCENTERPID), wait..."
			sleep 2
		done
		echo "imcenter is dead"
	fi
}
start() {
	startLogin
	sleep 1
	startIM
}
stop() {
	stopIM
	sleep 1
	stopLogin
}
restart() {
	stop;
	start;
}

#conditons
LOGINPID=`pgrep loginmgr`
CENTERPID=`pgrep corecenter`
FRONTPID=`pgrep front`
SMPID=`pgrep session`
IMCENTERPID=`pgrep imcenter`

#logic
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	startlogin)
		startLogin
		;;
	stoplogin)
		stopLogin
		;;
	startim)
		startIM
		;;
	stopim)
		stopIM
		;;
	help|*)
		echo $"Usage: $0 {start|stop|restart|startLogin|stopLogin|startIM|stopIM}"
		cat <<EOF

			start       - start all server
			stop        - stop all server
			restart     - restart all server
			startLogin  - start corecenter && loginmgr
			stopLogin   - stop loginmgr && corecenter
			startIM     - start imcenter && session1 && session2 && front
			stopIM      - stop front && all session && imcenter

EOF
		exit 1
		;;	
esac

exit 0
